package it.saga.pes.business;

import java.beans.Encoder;
import java.beans.Expression;
import java.beans.PersistenceDelegate;
import java.beans.XMLEncoder;
import java.util.Date;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;

public class CustomPersistenceDelegate extends PersistenceDelegate {

	private static SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

	protected Expression instantiate(Object obj, Encoder out) {
		if (obj instanceof byte[]) {
			byte[] e = (byte[]) obj;
			return new Expression(e, CustomPersistenceDelegate.class, "decode", new Object[] { CustomPersistenceDelegate.encode(e) });
		}
		if (obj instanceof org.exolab.castor.types.Date) {
			return new Expression(obj, org.exolab.castor.types.Date.class, "new", new Object[] { obj.toString() });
		} else if (obj instanceof Date) {
			return new Expression(obj, Date.class, "new", new Object[] { sdf.format(obj) });
		} else if (obj instanceof BigDecimal) {
			return new Expression(obj, BigDecimal.class, "new", new Object[] { obj.toString() });
		} else if (obj instanceof BigInteger) {
			return new Expression(obj, BigInteger.class, "new", new Object[] { obj.toString() });
		} else if (obj instanceof Integer) {
			return new Expression(obj, Integer.class, "new", new Object[] { obj.toString() });
		}
		return null;
	}

	public static String encode(byte[] data) {
		return new String(data);
	}

	public static String toXml(Object obj) throws Exception {
		ByteArrayOutputStream out = new ByteArrayOutputStream(10000);
		XMLEncoder xmlEncoder = new XMLEncoder(out) {
			public PersistenceDelegate getPersistenceDelegate(Class<?> type) {
				if (type == byte[].class)
					return new CustomPersistenceDelegate();
				else
					return super.getPersistenceDelegate(type);
			}
		};
		xmlEncoder.setPersistenceDelegate(org.exolab.castor.types.Date.class, new CustomPersistenceDelegate());
		xmlEncoder.setPersistenceDelegate(Date.class, new CustomPersistenceDelegate());
		xmlEncoder.setPersistenceDelegate(BigDecimal.class, new CustomPersistenceDelegate());
		xmlEncoder.setPersistenceDelegate(BigInteger.class, new CustomPersistenceDelegate());
		xmlEncoder.writeObject(obj);
		xmlEncoder.close();
		return out.toString();
	}
}
